/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import entity.DepartmentEntity;
import entity.InternalMessageEntity;
import entity.SystemUserEntity;
import java.util.HashSet;
import javax.persistence.PreUpdate;
import org.apache.log4j.Logger;

/**
 *
 * @author wei
 */
public class InternalMessageEntityListener {

    public InternalMessageEntityListener() {
    }

    @PreUpdate
    public void preUpdate(InternalMessageEntity message) {
        if (message.getSentAt() != null && !message.isForwaredToEmail()) {
            HashSet<SystemUserEntity> to = new HashSet<SystemUserEntity>();
            for (SystemUserEntity user : consolidateRecipients(message)) {
                if (user.getSetting().isForwardToEmail()) {
                    to.add(user);
                }
            }
            try {
                System.out.println("total recipients: " + to.size());
                Mailer.email(message.getSender(), to, null, message.getTitle(), message.getBody());
                message.setForwaredToEmail(true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private HashSet<SystemUserEntity> consolidateRecipients(InternalMessageEntity message) {
        HashSet<SystemUserEntity> usersFromDepartments = new HashSet<SystemUserEntity>();
        if (message.getDepartmentRecipients() != null) {
            for (DepartmentEntity d : message.getDepartmentRecipients()) {
                usersFromDepartments.addAll(d.getEmployees());
                d.getMessagesReceived().add(message);
            }
        }
        if (message.getRecipients() != null) {
            usersFromDepartments.addAll(message.getRecipients());
        }
        return usersFromDepartments;
    }
}
